/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.taglib;

import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.hibernate.Transaction;

import com.mr.qa.GlobalConfigs;
import com.mr.qa.bo.Answer;
import com.mr.qa.bo.Question;
import com.mr.qa.bo.QuestionCategory;
import com.mr.qa.dao.impl.QuestionCategoryDAO;
import com.mr.qa.dao.impl.QuestionDAO;
import com.mr.qa.util.HibernateSessionFactory;

public class QaUtilTag extends BodyTagSupport
{
    private Integer questionCategoryId;
    private String linksType;
    private Integer linksInOneLine = new Integer(1);//1 or 2
    private Integer totalLinks = new Integer(6);
    public QaUtilTag()
    {
        
    }
    public int doStartTag() throws JspException
    {
        try
        {
            JspWriter out = pageContext.getOut();
            if("A".equals(linksType))//article
                out.println(makeArticleLinks());
            else if("T".equals(linksType))//topic
                out.println(makeTopic());
            else if("R".equals(linksType))//recommend
                out.println(displayLatestRecommendedQuestions());
        }
        catch (Exception e)
        { 
            throw new JspException(e);
        }
        return EVAL_PAGE;
    }
    public int doEndTag() throws JspTagException 
    {
        return 0;
    }    
    /**
     * display the lastest survey(refered to as topic)
     * @return
     */
    private String makeTopic()
    {
        if(questionCategoryId == null || questionCategoryId.intValue() == 0)
            return "";
        Transaction tx = null;
        String html = "";
        try
        {
            HttpServletRequest request = (HttpServletRequest)this.pageContext.getRequest();
            QuestionCategoryDAO categoryDAO = new QuestionCategoryDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            QuestionCategory category = categoryDAO.findById(questionCategoryId);
            Collection list = category.getMrIaskQuestions();
            if(list.size() > 0)
            {
                Iterator<Question> ite = list.iterator();
                Question topic = null;
                Integer id;
                String title;
                String content;
                Set answers;
                while(ite.hasNext())
                {
                    topic = ite.next();
                    if("4".equals(topic.getState()))
                    {
                        continue;
                    }
                    id = topic.getId();
                    title = topic.getTitle();
                    content = topic.getContent();
                    answers = topic.getMrIaskAnswers();
                    html = "<a href='"+request.getContextPath()+"/question.mrqa?action=view&id="+id+"'>"+title+"</a><br>";
                    html = html + "<input type='hidden' name='id' value='"+id+"'/>";
                    /*
                    if(content != null && content.length() > 0)
                    {
                        html = html + content+"<br>";                        
                    }*/
                    Answer answer;
                    int totalVote = 0;                    
                    if(answers.size() > 0)
                    {
                        Iterator<Answer> ite1 = answers.iterator();
                        while(ite1.hasNext())
                        {
                            answer = ite1.next();
                            if("0".equals(answer.getState()))continue;
                            totalVote += answer.getPollCount();
                        }
                    }
                    if(totalVote == 0)totalVote = 1;
                    if(answers.size() > 0)
                    {
                        html = html + "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
                        Iterator<Answer> ite1 = answers.iterator();                    
                        while(ite1.hasNext())
                        {
                            answer = ite1.next();
                             if("0".equals(answer.getState()))continue;
                            html = html +"<tr>"+"<td><input type='checkbox' name='pollItem' value='"+answer.getId()+"'>"+answer.getContent()+"&nbsp;</td></tr>";
                            //html = html +"<tr>"+"<td><input type='checkbox' name='pollItem' value='"+answer.getId()+"'>"+answer.getContent()+"&nbsp;</td><td>"+"("+answer.getPollCount()+"/"+totalVote+")</td>"+"</tr>";
                        }
                        html = html+"</table>";
                    }
                    break;
                }
            }
            tx.commit();
        }
        catch(Exception e)
        {
            
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
        return html;
    }
    /**
     * make article links under a category
     * @return
     */
    private String makeArticleLinks()
    {
        if(questionCategoryId == null || questionCategoryId.intValue() == 0)
            return "";
        Transaction tx = null;
        String links = "";
        try
        {
            HttpServletRequest request = (HttpServletRequest)this.pageContext.getRequest();
            QuestionCategoryDAO categoryDAO = new QuestionCategoryDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            QuestionCategory category = categoryDAO.findById(questionCategoryId);
            Collection list = category.getMrIaskQuestions();
            if(list.size() > 0)
            {
                Iterator<Question> ite = list.iterator();
                Question topic = null;
                Integer id;
                String title;
                int size = 6;
                // if gong gao, the size is defined by GlobalConfigs.SIZE_GONGGAO
                if(totalLinks != null && totalLinks.intValue() > 0)
                {
                    size = totalLinks;
                }
                if (questionCategoryId.intValue() == 18){
                	size = GlobalConfigs.SIZE_GONGGAO_HOMEPAGE;
                }else if(questionCategoryId.intValue() == 19){
                	size = GlobalConfigs.SIZE_HELP_HOMEPAGE;
                }
                int i = 0;
                while(ite.hasNext() && i < size)
                {
                    topic = ite.next();
                    if("4".equals(topic.getState()))
                    {
                        continue;
                    }
                    id = topic.getId();
                    title = topic.getTitle();
                    if(links.length() > 0){
                        links = links+"<li><a href='"+request.getContextPath()+"/question.mrqa?action=view&id="+id+"'>";
                        if(topic.getTitleAttribute() != null && topic.getTitleAttribute().length() > 0){
                        	links = links + "<span style='" + topic.getTitleAttribute() + "'>";
                        }
                    	links = links + title;
                    	if(topic.getTitleAttribute() != null && topic.getTitleAttribute().length() > 0){
                        	links = links + "</span>";
                        }
                    	links = links + "</a>";
                    }
                    else{
                        links = "<li><a href='"+request.getContextPath()+"/question.mrqa?action=view&id="+id+"'>";
                        if(topic.getTitleAttribute() != null && topic.getTitleAttribute().length() > 0){
                        	links = links + "<span style='" + topic.getTitleAttribute() + "'>";
                        }
                        links = links +title;
                        if(topic.getTitleAttribute() != null && topic.getTitleAttribute().length() > 0){
                        	links = links + "</span>";
                        }
                        links = links + "</a>";
                    }
                    i = i+1;
                }
            }
            tx.commit();
        }
        catch(Exception e)
        {
            
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
        return links;
    }
    /**
     * display five recommended questions on home page
     * @depredicated
     * @return
     */
    private String displayLatestRecommendedQuestions()
    {
        String html = "";
        Transaction tx = null;
        try
        {
            HttpServletRequest request = (HttpServletRequest)this.pageContext.getRequest();
            String contextPath = request.getContextPath();
            QuestionDAO questionDAO = new QuestionDAO();
            questionDAO.setPage(1,5);
            tx = HibernateSessionFactory.getSession().beginTransaction();
            Collection list = questionDAO.findRecommendedAll();
            tx.commit();
            if(list.size() == 0)return "";
            Iterator<Question> ite = list.iterator();
            Question question = null;
            Answer answer = null;
            Integer id = null;
            String title = "";
            String content = "";
            int i = 0;
            String navigationLinks = "";
            String contentDivs = "";
            while(ite.hasNext())
            {
                question = ite.next();
                id = question.getId();
                title = question.getTitle();
                if(question.getMrIaskAnswers().size() > 0)
                {
                    answer = (Answer)question.getMrIaskAnswers().iterator().next();
                    content = answer.getContent();
                    if(content.length() > 75)
                    {
                        content = content.substring(0,74)+"....";
                    }
                }
                //html += "divContent["+i+"] = \"<a href='"+contextPath+"/question.mrqa?action=view&id="+id+"'><b>"+title+"</b></a><pre>"+content+"</pre>\";\n";
                contentDivs += "<div style='display:none' id='req"+i+"'><a href='"+contextPath+"/question.mrqa?action=view&id="+id+"'><b>"+title+"</b></a><pre>"+content+"</pre></div>\n";
                navigationLinks += "<span seqNo='"+i+"' onclick='show(this.seqNo);' style='cursor:hand;background-color:#FFA500;font-weight:bold;'>&nbsp;"+(i+1)+"&nbsp;</span>\n";
                i = i+1; 
                if(i == 5)
                {
                    navigationLinks += "<span onclick=\"more();\" style=\"cursor:hand;background-color:#FFA500;font-weight:bold;\" title=\"more\">>></span>\n";
                    break;
                }
            }
            html = contentDivs+navigationLinks
            +"<script language=\"Javascript\" type=\"text/javascript\">\n"
            +"var divContent = new Array("+i+");\n"+html;
            if(i>= 1)
            {
                html = html + "show(0);\n";
            }
            html = html + "function show(seqNo)\n";
            html = html + "{\n";
            html = html + "var reqDiv = document.getElementById(\"req\"+seqNo);\n";
            //html = html + "alert(reqDiv.innerHTML);\n";
            html = html + "var rqDiv = document.getElementById(\"rq\");\n";
            html = html + "rqDiv.innerHTML = reqDiv.innerHTML;\n";
            html = html + "}\n";
            html = html + "function more()\n";
            html = html + "{\n";
            html = html + "document.location.href='"+contextPath+"/question.mrqa?action=recommendedlist';\n";
            html = html + "}\n";
            html = html + "</script>\n";
        }
        catch(Exception e)
        {
        }
        finally
        {
            HibernateSessionFactory.closeSession();
        }
        return html;                
    }



    public void setQuestionCategoryId(Integer questionCategoryId)
    {
        this.questionCategoryId = questionCategoryId;
    }
    
    public Integer getQuestionCategoryId()
    {
        return questionCategoryId;
    }
    
    public void setLinksType(String linksType)
    {
        this.linksType = linksType;
    }
    
    public String getLinksType()
    {
        return linksType;
    }
    
    public void setLinksInOneLine(Integer linksInOneLine)
    {
        this.linksInOneLine = linksInOneLine;
    }
    
    public Integer getLinksInOneLine()
    {
        return linksInOneLine;
    }
    
    public void setTotalLinks(Integer totalLinks)
    {
        this.totalLinks = totalLinks;
    }
    
    public Integer getTotalLinks()
    {
        return totalLinks;
    }
}
